<template>
  <div class="client-manager-dialog">
    <el-dialog v-model="isShowDialog" width="474" :align-center="true" :show-close="false" :close-on-click-modal="false">
      <template #header>
        <title-view :title="dialogTitle"></title-view>
      </template>
      <el-form ref="ruleFormRef" :model="clientManagerForm" :rules="clientManagerRules" label-width="80px" status-icon>
        <el-form-item label="项目角色" prop="roleId">
          <el-select v-model="clientManagerForm.roleId" @change="handelRoleChange">
            <el-option v-for="item in roleData" :key="item.roleId" :label="item.roleName" :value="item.roleId" />
          </el-select>
        </el-form-item>
        <el-form-item label="部门" prop="deptId">
          <el-cascader
            ref="deptRoleRef"
            v-model="clientManagerForm.deptId"
            :show-all-levels="false"
            :options="deptTrees"
            :props="cascaderProps"
            clearable
            @change="cascaderChange"
          />
        </el-form-item>
        <el-form-item label="员工姓名" prop="userId">
          <el-select v-model="clientManagerForm.userId" filterable placeholder="请输入关键字或选择" @change="changeUser">
            <el-option v-for="item in userData" :key="item.userId" :label="item.nickName" :value="item.userId" />
          </el-select>
        </el-form-item>
        <!--        <el-form-item label="客户画像" prop="portaintId">-->
        <!--          <el-select v-model="clientManagerForm.portaintId">-->
        <!--            <el-option v-for="item in customerProfile" :key="item.value" :label="item.label" :value="item.value" />-->
        <!--          </el-select>-->
        <!--        </el-form-item>-->
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="handelClose" size="large">取消</el-button>
          <el-button type="primary" @click="handelSubmit" :loading="isSubmit" size="large">确定</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, computed, getCurrentInstance, nextTick } from "vue";
import { allocationTransferForm, allocationTransferType } from "@/views/client/clientManager/config";
import { getAssignRole as assignRole, clientAssign } from "@/apis/clientManager";
import { departmentTree, userDeptByUserId, userListByRole } from "@/apis/user";
import { filterPortraitList } from "@/apis/dict/dict";
import useUserStore from "@/store/modules/user";

const emit = defineEmits(["update:modelValue"]);
const props = defineProps({
  modelValue: {
    type: Boolean,
    default: false
  },
  dialogTitle: {
    type: String,
    default: ""
  },
  optionType: {
    type: Number,
    default: allocationTransferType.ALLOCATION
  },
  customerIds: {
    type: Array,
    default: () => []
  }
});
const userStore = useUserStore();
const { proxy } = getCurrentInstance();

const isShowDialog = computed({
  get() {
    return props.modelValue;
  },
  set(val) {
    emit("update:modelValue", val);
  }
});
const isSubmit = ref(false);
const clientManagerForm = ref({ ...allocationTransferForm });
const clientManagerRules = {
  roleId: [{ required: true, message: "请选择项目角色", trigger: "change" }],
  deptId: [{ required: true, message: "请选择部门", trigger: "change" }],
  userId: [{ required: true, message: "请选择员工", trigger: "change" }],
  portaintId: [{ required: true, message: "请选择业务类型", trigger: "change" }]
};

const roleData = ref([]);
const getAssignRole = async () => {
  const { data } = await assignRole();
  roleData.value = data || [];
};

const deptTrees = ref([]);
const getDeptTree = async () => {
  const { data } = await departmentTree();
  deptTrees.value = data || [];
};

const getUserDept = async () => {
  const { data } = await userDeptByUserId(userStore.userInfo.userId);
  deptTrees.value = data || [];
};

const userData = ref([]);
const getUserData = async () => {
  const params = {
    deptId: clientManagerForm.value.deptId,
    roleId: clientManagerForm.value.roleId
  };
  const { data } = await userListByRole(params);
  userData.value = data || [];
};

const handelRoleChange = val => {
  let canAllDepts = false;
  clientManagerForm.value.deptName = "";
  clientManagerForm.value.deptId = "";
  clientManagerForm.value.userName = "";
  clientManagerForm.value.userId = "";
  roleData.value.some(item => {
    if (val === item.roleId) {
      canAllDepts = item.canAllDepts;
      return true;
    }
  });
  canAllDepts ? getDeptTree() : getUserDept();
};

const cascaderProps = {
  checkStrictly: true,
  emitPath: false,
  value: "deptId",
  label: "deptName"
};
const cascaderChange = () => {
  const selectNode = proxy.$refs.deptRoleRef.getCheckedNodes();
  clientManagerForm.value.deptName = selectNode?.[0]?.label ?? "";
  clientManagerForm.value.userName = "";
  clientManagerForm.value.userId = "";
  getUserData();
};

const changeUser = val => {
  const selectData = userData.value.find(item => item.userId === val);
  clientManagerForm.value.userName = selectData?.nickName || "";
};

const customerProfile = ref([]);
const getPortraitList = async () => {
  const { data } = await filterPortraitList();
  if (data?.length) {
    customerProfile.value = data.map(item => {
      return {
        label: item.portraitName,
        value: item.portraitId
      };
    });
  }
};

const handelSubmit = () => {
  proxy.$refs.ruleFormRef.validate(async val => {
    if (!val) {
      return proxy.$modal.msgError("请填写完整信息");
    }
    try {
      isSubmit.value = true;
      clientManagerForm.value.type = props.optionType;
      clientManagerForm.value.customerIds = props.customerIds;
      await clientAssign(clientManagerForm.value);
      isSubmit.value = false;
      proxy.$modal.msgSuccess(`${clientManagerForm.value.type === allocationTransferType.ALLOCATION ? "分配" : "移交"}成功`);
      handelClose();
    } catch (err) {
      isSubmit.value = false;
    }
  });
};
const handelClose = async () => {
  await nextTick();
  proxy.$refs.ruleFormRef.resetFields();
  clientManagerForm.value = {
    ...allocationTransferForm
  };
  deptTrees.value = [];
  userData.value = [];
  isShowDialog.value = false;
};

getAssignRole();
getPortraitList();
</script>

<style scoped lang="scss">
@use "AllocationTransfer";
</style>
